package com.swcw.platform.utils;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.swcw.platform.wlwLog.service.IWlwLogService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.swcw.platform.external.bean.OwnUsers;
import com.swcw.platform.external.constants.Pagination;
import com.swcw.platform.external.service.IOwnUsersService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.processors.JsDateJsonValueProcessor;
import net.sf.json.util.PropertyFilter;

/**
 * 抽取公共response与request字段
 * 
 * @author 杨坚
 * @version [版本号, 2016年3月17日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class BaseRquestAndResponse {
	
	/**
	 * 全局导入字段，true 导入中  false 正常
	 */
	private static boolean importFlag = false;
	
	protected static final String RELOAD = "reload";

	protected static final String VIEW = "view";

	protected static final String EDIT = "edit";

	protected static final String LIST = "list";
	
	protected static final String JSON_ERROR = "Json Converted Error";

    protected static final String TOTAL = "\"total\":";

    protected static final String ROWS = "\"rows\":";

    protected static final String ENCODING = "utf-8";
	
    protected static Logger logger = LoggerFactory.getLogger(BaseRquestAndResponse.class);
    
	@Autowired
	private IOwnUsersService ownUsersService;// 用户

	@Autowired
	private IWlwLogService wlwLogService;

	//获取request请求HttpServletRequest 
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	// 获取response请求
	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}

	// 获取session请求
	public static HttpSession getSession() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
	}
	
	/**
	 * 保存导入进度
	 */
	public static void importSchedule(Integer totalrows,Integer i) {
		getSession().setAttribute("totalrows", totalrows);
		getSession().setAttribute("row", i);
	}
	
	/**
	 * 保存导入进度
	 */
	public static void getImportSchedule(Integer totalrows,Integer i) {
		getSession().setAttribute("totalrows", totalrows);
		getSession().setAttribute("row", i);
	}
	
	/**
	 * 返回字符串到前台
	 * @param str
	 * @author 郑建超
	 * @Time 2017年1月3日
	 * @version 1.0v
	 */
	public static void returnString(String str) {
		if(str == null){
			str = "";
		}
		try {
			getResponse().getWriter().println(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 返回json到前台
	 * @param result
	 * @author 郑建超
	 * @Time 2017年1月3日
	 * @version 1.0v
	 */
	public static void returnString(Map<String, Object> result) {
		String str = getJSONString(result);
		if(str == null){
			str = "";
		}
		try {
			//System.out.println("================="+str);
			getResponse().getWriter().println(str);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public OwnUsers getLoginUser()
	{
	    return ownUsersService.selectFindById((String)getSession().getAttribute("userId"));
	}
	
	public String getLoginUserId()
	{
	    return (String)getSession().getAttribute("userId");
	}
	
	/** 
	* 把数据对象转换成json字符串 
	* DTO对象形如：{"id" : idValue, "name" : nameValue, ...} 
	* 数组对象形如：[{}, {}, {}, ...] 
	* map对象形如：{key1 : {"id" : idValue, "name" : nameValue, ...}, key2 : {}, ...} 
	* @param object 
	* @return 
	*/ 
	public static String getJSONString(Object object){ 
		String jsonString = null; 
		//日期值处理器 
		JsonConfig jsonConfig = new JsonConfig(); 
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new JsDateJsonValueProcessor()); 
		if(object != null)
		{ 
			if(object instanceof Collection || object instanceof Object[])
			{ 
				jsonString = JSONArray.fromObject(object, jsonConfig).toString(); 
			}
			else
			{ 
				jsonString = JSONObject.fromObject(object, jsonConfig).toString(); 
			} 
		} 
		return jsonString == null ? "{}" : jsonString; 
	}

	public static boolean isImportFlag() {
		return importFlag;
	}

	public static void setImportFlag(boolean importFlag) {
		getSession().removeAttribute("totalrows");
		getSession().removeAttribute("row");
		BaseRquestAndResponse.importFlag = importFlag;
	} 
	
	/**
	 * 将对象做为json的分页数据输出
	 * 
	 * @param filter 需要输出的对象属性，多个以“,”隔开
	 * @param result 需要转成json的对象
	 */
	protected void outputJson(final String filter, Object result) {
		JsonConfig config = new JsonConfig();
		if (filter != null && filter.length() > 1) {
			config.setJsonPropertyFilter(new PropertyFilter() {

				@Override
				public boolean apply(Object source, String name, Object value) {
                    return filter.indexOf(name + "|") == -1;
				}
			});
		}
		JSONObject json = JSONObject.fromObject(result, config);

		try {
			getResponse().setContentType("text/html");
			getResponse().getWriter().println(json.toString());
		} catch (Exception e) {
			logger.error(JSON_ERROR, e);
		}
	}
	
	/**
	 * 将分页对象列做为json数据输出
	 * 
	 * @param pagination 分页对象
	 * @param config 输出json的配置对象
	 * @return
	 */
	public String convObjectToJson(Pagination pagination) {
		StringBuilder data = new StringBuilder("{\n");
		try {
			
			data.append(TOTAL).append(pagination.getTotalCount())
					.append(",\n");
			data.append(ROWS);
			JSONArray json = JSONArray.fromObject(pagination.getList());
			data.append(json.toString());
			data.append("  \n").append("}");
			getResponse().setContentType("application/json;charset=UTF-8");
			getResponse().setCharacterEncoding(ENCODING);
			getResponse().setHeader("Charset", ENCODING);
			getResponse().setHeader("Cache-Control", "no-cache");
			getResponse().getWriter().println(data);
		} catch (Exception e) {
			logger.error(JSON_ERROR, e);
		}
		return data.toString();
	}

	/**
	 * 保存日志
	 * @param user
	 * @param logs
	 * @param logType
	 * @param ip
	 */
	public void addLogs(OwnUsers user, String logs, String logType,String ip) {
		wlwLogService.addLogs(user, logs, logType, ip);
	}

	/**
	 * 获取用户真实IP地址，不使用request.getRemoteAddr();的原因是有可能用户使用了代理软件方式避免真实IP地址,
	 *
	 * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值，究竟哪个才是真正的用户端的真实IP呢？
	 * 答案是取X-Forwarded-For中第一个非unknown的有效IP字符串。
	 *
	 * 如：X-Forwarded-For：192.168.1.110, 192.168.1.120, 192.168.1.130,
	 * 192.168.1.100
	 *
	 * 用户真实IP为： 192.168.1.110
	 *
	 * @return
	 */
	public static String getIpAddress() {
		HttpServletRequest request = getRequest();
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
